<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>throttle</title>
</head>
<body>
<script>

    /*多次调用只记录第一次调用*/
    function  throtle1(f,ms){
        let called =false
        return  function (...args){
            if (called) {
                return
            }
            called = true

            setTimeout(()=>{
                f.apply(this,args)
                called =false

            },ms)
        }
    }

/*多次调用记录最后一次的调用*/
    function  throtle2(f,ms){
        let called =false
        let recordThis,recordArg
        return  function (...args){
            recordThis =this
            recordArg= args
            if (called)  return
            called = true

            setTimeout(()=>{
                f.apply(recordThis,recordArg)
                called =false
                recordThis = null
                recordArg =null

            },ms)
        }
    }


    /*第一次调用同步执行，后面的调用走节流*/
    function  throtle3(f,ms){
        let isFirst =true
        let called =false
        let recordThis,recordArg
        return  function (...args){
            recordThis =this
            recordArg= args
            if (called) {
                return
            }
            called = true

            if (isFirst){
                f.apply(recordThis,recordArg)
                isFirst =false
            }

            setTimeout(()=>{
                f.apply(recordThis,recordArg)
                called =false
                recordThis = null
                recordArg =null

            },ms)
        }
    }



    /*
    * 多考虑代码复用而不是分情况讨论
    *
    * */
    function throttle (f,ms) {
        let throttled =false,
            saveThis,
            saveArgs

         function wrapper (...args) {
            if (throttled){
                saveArgs = args
                saveThis = this
                return
            }
              f.apply(this,args)

             setTimeout(()=>{
                 if (saveArgs){
                     wrapper.apply(saveThis,saveArgs)
                     saveThis =null
                     saveArgs =null
                 }

             },ms)

        }
        return wrapper
    }

    let foo = throttle(n =>{
        console.log(n)},2000)

    foo(1)
</script>
</body>
</html>